<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\common\helper\util\Page;
use app\common\logic\category\Category;
use app\exam\logic\admin\PaperConfig as PaperConfigLogic;
use app\exam\model\admin\ModuleExamination as ModuleExaminationModel;
use think\annotation\Inject;

/**
 * Class ModuleExamination
 *
 * @package app\exam\logic\admin
 */
class ModuleExamination extends ModuleExaminationModel
{
    /**
     * @Inject
     *
     * @var Category
     */
    protected $category;

    /**
     * @Inject()
     *
     * @var Paper
     */
    protected $paperLogic;

    /**
     * 获取试题列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param array $map
     * @param array $paperWhere
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [], array $paperWhere = [])
    {
        return $this
            ->hasWhere('paper', $paperWhere)
            ->with(['paper'])
            ->where($map)
            ->paginate(Page::listRows())->each(function ($item) {
                $item->cate_title = $this->category->parseTitle($item->getAttr('category'), 3);
                // 获取价格
                $config       = app(PaperConfigLogic::class)->get('examination_' . $item->module_id, $item->paper_id);
                $item->price = $config['price'] ?? '';
            });

    }

    /**
     * 获取选择面板数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getChooseList(int $moduleId, array $map = [])
    {
        return $this->paperLogic
            ->where($map)
            ->order('update_time', 'desc')
            ->paginate(Page::listRows())
            ->each(function ($item) use ($moduleId) {
                $item->cate_title = $this->category->parseTitle($item->category, 3);
                // 判断是否已经选择了
                $hasPaper      = $this->where('module_id', $moduleId)->where('paper_id', $item->getAttr('id'))->value('id');
                $item->checked = !!$hasPaper;
            })->append(['paper_type_text']);
    }

    /**
     * 新增绑定的试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int   $moduleId
     * @param array $papers
     * @throws \Exception
     */
    public function createModuleExaminationPaper(int $moduleId, array $papers)
    {
        $saveAll = [];
        foreach ($papers as $paper) {
            $saveAll[] = [
                'module_id' => $moduleId,
                'paper_id'  => $paper
            ];
        }

        $ret = $this->replace()->saveAll($saveAll);

        if (!$ret) {
            throw new LogicException('关联失败');
        }

        Log::write('新建公开考试试卷【' . $moduleId . '/' . implode(',', $papers) . '】', 'exam', 'create', true);
    }

    /**
     * 根据ID获取信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int $examinationId
     * @return array|\think\Model
     */
    public function getModuleExaminationPaperById(int $examinationId)
    {
        return $this->findOrFail($examinationId);
    }

    /**
     * 编辑
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int $examinationId
     * @param     $field
     * @param     $value
     * @return array|\think\Model
     */
    public function editModuleExaminationPaper(int $examinationId, $param)
    {
        // 信息
        $examination = $this->getModuleExaminationPaperById($examinationId);

        foreach ($param as $k => $v) {
            $examination->$k = $v;
        }

        if (!$examination->save()) {
            throw new LogicException("更新失败");
        }

        Log::write('编辑公开考试试卷【' . $examination->title . '/' . $examinationId . '】', 'exam', 'update', true);

        // 返回值
        return $examination;
    }

    /**
     * 编辑字段信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int $examinationId
     * @param     $field
     * @param     $value
     * @return array|\think\Model
     */
    public function editModuleExaminationPaperField(int $examinationId, $field, $value)
    {
        // 信息
        $examination = $this->getModuleExaminationPaperById($examinationId);

        $examination->$field = $value;

        if (!$examination->save()) {
            throw new LogicException("更新失败");
        }

        Log::write('编辑公开考试【' . $examination->title . '/' . $examinationId . '】', 'exam', 'update', true);

        // 返回值
        return $examination;
    }

    /**
     * 移除试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/3
     *
     * @param string $ids
     */
    public function deleteModuleExaminationPaper(string $ids)
    {
        $res = $this->whereIn('id', $ids)->selectOrFail()->delete();
        if (!$res) {
            throw new LogicException('移除失败');
        }

        Log::write('移除试卷【' . $ids . '】', 'exam', 'delete', true);
    }
}